import OSS from "ali-oss";

interface fileInput {
  name: string;
  size: number;
  type: string;
  raw: File;
}

const upload = async (fileInput: fileInput) => {
  if (!fileInput) {
    alert("请先选择文件");
    return;
  }

  console.log("选择的文件:", fileInput.name, "大小:", fileInput.size);
  const client = new OSS({
    region: "oss-cn-beijing",
    accessKeyId: "LTAI5tLgty8ksyhj5XZLZLqS",
    accessKeySecret: "PPXGC5Y8IK5pRF1iuJOgpu8qBttshs",
    bucket: "mybucketwkcccccc",
  });

  try {
    // 编码文件名，避免中文字符问题
    const encodeFileName = (name: string) => {
      try {
        return encodeURIComponent(fileInput.name); //js内置函数
      } catch (e) {
        // 如果编码失败，使用时间戳作为文件名
        return `file_${Date.now()}`;
      }
    };

    // 使用实际文件名，添加时间戳避免重名
    const timestamp = new Date().getTime();
    const safeFileName = encodeFileName(fileInput.name);
    const fileName = `uploads/${timestamp}_${safeFileName}`;

    const options = {
      meta: {
        uploadTime: new Date().toISOString(),
        // 不直接使用原始文件名，避免中文字符问题
        originalName: safeFileName,
        fileSize: fileInput.size.toString(),
        fileType: fileInput.type || "application/octet-stream",
      },
      mime: fileInput.type || "application/octet-stream",
    };

    const result = await client.put(fileName, fileInput.raw, options as any);
    console.log(result, "resultOss");

    return result;
  } catch (e) {
    console.error("上传失败:", e);

    return null;
  }
};

export default upload;
